package com.wanxi.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wanxi.dao.ManagerDao;
import com.wanxi.dto.ResultDTO;
import com.wanxi.model.Manager;
import com.wanxi.service.ManagerService;
import com.wanxi.util.CreateOnlyID;
import com.wanxi.util.JsonCopy;
import com.wanxi.util.Md5;
import com.wanxi.vo.ManagerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author Chengbo Zhang
 */
@Service
@Transactional
public class ManagerServiceImpl implements ManagerService {
    @Autowired
    ManagerDao managerDao;
    @Autowired
    CreateOnlyID createOnlyId;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public ResultDTO findAllManager() {
        List<Manager> list = managerDao.findAll();
//        保证密码不泄露
        if (list.size() > 0) {
            list.forEach(manager -> {
                manager.setPassword("******");
            });
            return ResultDTO.getDTO(list.size(), list);
        } else {
            return ResultDTO.builder().count(0).data(list).msg("no data").build();
        }
    }

    @Override
    public ResultDTO findManagerById(ManagerVO managerVO) {
        Manager manager = Manager.builder()
                .id(managerVO.getId())
                .build();
        Manager m = managerDao.findById(manager.getId());
        if (m != null) {
            m.setPassword("******");
            return ResultDTO.getDTO(1, m);
        } else {
            return ResultDTO.builder().count(0).msg("no found").code(1).build();
        }
    }

    @Override
    public ResultDTO addManager(ManagerVO managerVO) {
        Manager manager = Manager.builder()
                .id(createOnlyId.createId())
                .managerName(managerVO.getManagerName())
                .password(Md5.encoderByMd5(managerVO.getPassword()))
                .enable(managerVO.getEnable())
                .remark(managerVO.getRemark())
                .updateTime(new Date())
                .createTime(new Date())
                .build();
        if (managerVO.getEnable() == null) {
            manager.setEnable(0);
        }
        QueryWrapper<Manager> queryWrapper = new QueryWrapper<Manager>()
                .eq(manager.getManagerName() != null, "managerName", manager.getManagerName());
        Manager m = managerDao.selectOne(queryWrapper);
        if (m == null) {
            int i = managerDao.insert(manager);
            if (i == 1) {
                if(Objects.nonNull(managerVO.getRoleIds())){
                    for (Long roleId :
                            managerVO.getRoleIds()) {
                        Long id = createOnlyId.createId();
                        managerDao.addRoles(id,manager.getId(),roleId );
                    }
                }
                return ResultDTO.getDTO(i, managerVO);
            }
        }
        return ResultDTO.builder().code(1).count(0).msg("error").data(managerVO).build();
    }

    @Override
    public ResultDTO updatePassword(ManagerVO managerVO) {
        if (managerVO.getOldPassword() != null && !"".equals(managerVO.getOldPassword())) {
            Manager manager = Manager.builder()
                    .id(managerVO.getId())
                    .password(Md5.encoderByMd5(managerVO.getOldPassword()))
                    .updateTime(new Date())
                    .build();
            Long managerId = manager.getId();
            String password = manager.getPassword();
            QueryWrapper<Manager> queryWrapper = new QueryWrapper<Manager>()
                    .eq(managerId != null, "id", managerId)
                    .eq(password != null && !"".equals(password), "password", password);
            Manager m = managerDao.selectOne(queryWrapper);
            if (m != null) {
                manager.setPassword(Md5.encoderByMd5(managerVO.getNewPassword()));
                int i = managerDao.updateById(manager);
                if (i == 1) {
                    stringRedisTemplate.delete("loginManager");
                    return ResultDTO.getDTO(i, managerVO);
                }
            }
            return ResultDTO.builder().msg("原密码错误").count(0).code(1).data(managerVO).build();
        }
        return ResultDTO.builder().msg("error").count(0).code(1).data(managerVO).build();
    }

    @Override
    public ResultDTO deleteManager(ManagerVO managerVO) {
        Manager manager = Manager.builder().id(managerVO.getId()).build();
        int i = managerDao.deleteById(manager);
        if (i == 1) {
            managerDao.deleteRoleOfManager(manager);
            return ResultDTO.getDTO(i, managerVO);
        }
        return ResultDTO.builder().count(0).data(managerVO).code(1).msg("error").build();
    }

    @Override
    public ResultDTO updateById(ManagerVO managerVO) {
        Manager manager = new Manager();
        manager.setId(managerVO.getId());
        manager.setManagerName(managerVO.getManagerName());
        manager.setRemark(managerVO.getRemark());
        manager.setUpdateTime(new Date());
        if (managerVO.getId() != null) {
            Manager m = managerDao.selectById(manager.getId());
//            密码处理
            if (managerVO.getPassword() != null && "1".equals(managerVO.getPassword())) {
                manager.setPassword(Md5.encoderByMd5(null));
            } else if (managerVO.getPassword() == null || "0".equals(managerVO.getPassword())) {
                manager.setPassword(m.getPassword());
            }
//            状态处理
            if (managerVO.getEnable() == null) {
                manager.setEnable(m.getEnable());
            } else {
                manager.setEnable(managerVO.getEnable());
            }
//            用户名处理
            if (managerVO.getManagerName() == null) {
                manager.setManagerName(m.getManagerName());
            }
//            角色处理
            int i = managerDao.updateById(manager);
            if (i == 1) {
                managerDao.deleteRoleOfManager(manager);
                if(Objects.nonNull(managerVO.getRoleIds())){
                    for (Long roleId :
                            managerVO.getRoleIds()) {
                        Long id = createOnlyId.createId();
                        managerDao.addRoles(id,managerVO.getId(),roleId );
                    }
                }
                return ResultDTO.getDTO(i, managerVO);
            }
        }
        return ResultDTO.builder().msg("error").code(1).count(0).data(managerVO).build();
    }

    @Override
    public ResultDTO updateEnable(ManagerVO managerVO) {
        Manager manager = Manager.builder()
                .id(managerVO.getId())
                .enable(managerVO.getEnable())
                .updateTime(new Date())
                .build();
        if (managerVO.getEnable() == null) {
            manager.setEnable(0);
        }
        int i = managerDao.updateById(manager);
        if (i == 1) {
            return ResultDTO.getDTO(i, managerVO);
        }
        return ResultDTO.builder().data(managerVO).count(0).code(1).msg("error").build();
    }

    @Override
    public ResultDTO findManagerBySome(ManagerVO managerVO) {
        Manager manager = JsonCopy.copy(managerVO, Manager.class);
        String managerName = manager.getManagerName();
        QueryWrapper<Manager> queryWrapper = new QueryWrapper<Manager>()
                .like(managerName != null && !"".equals(managerName), "managerName", managerName)
                .gt(manager.getCreateTime() != null, "createTime", manager.getCreateTime())
                .orderByDesc("id");
        List<Manager> list = managerDao.selectList(queryWrapper);
//        保证密码不泄露
        if (list.size() > 0) {
            list.forEach(m -> {
                m.setPassword("******");
            });
            return ResultDTO.getDTO(list.size(), list);
        } else {
            return ResultDTO.builder().count(0).data(list).msg("no data").build();
        }
    }
}
